<!--
 * @Author: your name
 * @Date: 2020-06-19 11:26:01
 * @LastEditTime: 2020-09-16 10:18:08
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \sanitation-web\src\views\modules\site\site-management-map.vue
-->
<template>
  <div v-if="visible">
    <el-dialog :visible.sync="visible"
               title="请选择地址"
               :modal="false"
               class="user-dialog"
               :before-close="closeDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <div style="height:400px; position: relative;"
           v-loading='mapLoading'
           :element-loading-text="loadingMsg">
        <div id="container"></div>
        <div class="search-operating">
          <el-radio-group v-model="type"
                          class="margin-bottom-10"
                          size="mini"
                          @change="changeType">
            <el-radio-button label="1">地址查询</el-radio-button>
            <el-radio-button label="2">坐标查询</el-radio-button>
          </el-radio-group>
          <div class="search-input-box th"
               :style="searchWidth">
            <el-input v-model.trim="addrValue"
                      :placeholder="inputPlaceholder"
                      clearable
                      class="search-input"
                      size="mini"></el-input>
            <el-button type="primary"
                       v-if="type === '2'"
                       class="margin-left-10"
                       @click="selectAddr(addrValue)"
                       size="mini">查询</el-button>
          </div>
          <div class="search-list theme-bg-color"
               v-show="searchList.length && type !== '2'">
            <div class="search-item margin-bottom-10"
                 @click="selectAddr(item.location)"
                 v-for="(item,index) of searchList"
                 :key="index">
              <span>{{item.name || ''}}</span>
              <span class="info-color margin-left-20">{{item.district || ''}}</span>
            </div>
          </div>
        </div>
        <div class="addr">{{address}}</div>
      </div>
      <template slot="footer">
        <el-button @click="closeDialog()">{{ $t('cancel')}}</el-button>
        <el-button type="primary"
                   @click="dataFormSubmitHandle()">{{ $t('confirm')}}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import debounce from 'lodash/debounce'
export default {
  mixins: [mixinViewModule],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '', // 数据列表接口，API地址
        getDataListIsPage: true, // 数据列表接口，是否需要分页？
        addOrUpdateURL: '', // 添加或修改接口，API地址
        getDataInfoURL: '', // 数据详情，API地址
        deleteURL: '', // 删除接口，API地址
        deleteIsBatch: true, // 删除接口，是否需要批量？
        exportURL: '' // 导出接口，API地址
      },
      searchWidth: {
        width: '160px'
      },
      inputPlaceholder: '请输入地址进行查询',
      type: '1',
      searchList: [],
      addrValue: '',
      autoComplete: '',
      geocoder: '',
      visible: false,
      mapLoading: false,
      loadingMsg: '地图加载中...',
      lnglat: '',
      address: '',
      map: ''
    }
  },
  watch: {
    addrValue (val) {
      const self = this
      this.searchList = []
      if (val === '') { return false }
      this.autoComplete.search(val, function (status, result) {
        self.searchList = []
        // 搜索成功时，result即是对应的匹配数据
        if (status !== 'complete') {
          self.searchList.push({
            name: '暂无数据'
          })
          return false
        }
        self.searchList.push(...result.tips)
      })
    }
  },
  computed: {
    // 设置表单规则
  },
  methods: {
    closeDialog () {
      this.visible = false
    },
    init (data) {
      this.visible = true
      this.mapLoading = true
      this.address = ''
      this.lnglat = ''
      const self = this
      let autoComplete = ''
      this.$nextTick(() => {
        let map = new AMap.Map('container', {
          zoom: 11,
          center: [113.75, 23.05],
          showIndoorMap: false
        })

        map.on('complete', function () {
          self.mapLoading = false
        })

        let marker = new AMap.Marker()
        AMap.plugin(['AMap.Geocoder', 'AMap.Autocomplete'], function () {
          self.geocoder = new AMap.Geocoder()
          // 实例化Autocomplete
          let autoOptions = {
            // city 限定城市，默认全国
            city: '全国'
          }
          autoComplete = new AMap.Autocomplete(autoOptions)
        })

        map.on('click', function (e) {
          map.clearMap()
          map.add(marker)
          marker.setPosition(e.lnglat)
          self.$nextTick(() => {
            self.regeoCode(e.lnglat)
          })
        })

        this.map = map
        this.autoComplete = autoComplete
      })
    },
    // 修改查询类型
    changeType (val) {
      if (val === '1') {
        this.searchWidth.width = '160px'
        this.inputPlaceholder = '请输入地址进行查询'
      } else {
        this.searchWidth.width = '225px'
        this.inputPlaceholder = '请输入坐标进行查询'
      }
    },
    // 查询
    selectAddr (lnglat) {
      this.map.clearMap()
      if (!lnglat) { return }

      if (typeof lnglat === 'string') {
        lnglat = lnglat.split(',')
      }

      if (lnglat.length <= 1) {
        this.address = ''
        this.lnglat = ''
        this.$message.warning('输入坐标无效或格式错误')
        return false
      }

      this.map.setCenter(lnglat)
      this.map.setZoom(16)
      this.regeoCode(lnglat)
      const startMarker = new AMap.Marker({
        position: lnglat
      })
      this.map.add(startMarker)
      this.searchList = []
      this.addrValue = ''
    },
    // 根据坐标获取物理地址
    regeoCode (lnglat) {
      const self = this
      this.geocoder.getAddress(lnglat, function (status, result) {
        if (status === 'complete' && result.regeocode) {
          var address = result.regeocode.formattedAddress
          self.address = address
          self.lnglat = lnglat
        } else {
          self.$message.warning('根据经纬度查询地址失败')
        }
      })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.closeDialog()
      this.$emit('callBack', this.address, this.lnglat)
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss" scoped>
#container {
  width: 100%;
  height: 100%;
  margin: 0px;
}
.search-operating {
  position: absolute;
  top: 10px;
  left: 10px;
  // display: flex;
  width: 100%;
  .search-input-box {
    width: 160px;
    display: flex;
    .search-input {
      flex: 1;
    }
  }
  .search-list {
    position: absolute;
    top: 66px;
    left: 0px;
    min-width: 165px;
    border-radius: 4px;
    padding: 10px;
    padding-bottom: 0;
    .search-item {
      cursor: pointer;
    }
  }
}
.addr {
  height: 20px;
  padding: 10px;
}
</style>
